import java.util.Arrays;

/**
 * @program: 2022.3.7复习
 * @description:
 * @author: 李鑫月
 * @create: 2022-03-09 17:19
 **/
public class MyArrayList<E> {
    private Object[] elem;
    private int usedSize;
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    public MyArrayList() {
        this.elem = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

    }
    public MyArrayList(int capacity){
        if(capacity>=0){
            this.elem=new Object[capacity];
        }else{
            throw new IllegalArgumentException("容量不合法:"+capacity);
        }
    }
    /** 
    * @Description: 添加元素 
    * @Param:  
    * @return:  
    * @Author: Mr.Wang 
    * @Date: 2022/3/9 
    */ 
    public boolean add(E e){
        ensureCapacityInternal(usedSize + 1);  // Increments modCount!!
        elem[usedSize++]=e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity) {
        int ret=calculateCapacity(elem, minCapacity);
        ensureExplicitCapacity(ret);

    }

    private void ensureExplicitCapacity(int minCapacity) {


        // overflow-conscious code
        if (minCapacity - elem.length > 0)
            grow(minCapacity);
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
    //1.是否之前分配过内存ma
        if (elementData==DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
        return Math.max(10,minCapacity);
        }
        //2 分配过,就返回+1后的值
    return minCapacity;
    }
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elem.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - Integer.MAX_VALUE-8 > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elem = Arrays.copyOf(elem, newCapacity);
    }
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > Integer.MAX_VALUE) ?
                Integer.MAX_VALUE :
                Integer.MAX_VALUE-8 ;
    }
    public void add(int index,E e){

    }

}
